import {defineStore} from 'pinia'
import {reqCartList, reqDelCartById, reqUpdateChekedById} from '@/api'
import {CartType} from '@/store/types'
//shopcart模块的仓库
export const useShopCartStore = defineStore('shopcart', {
    state: () => ({
        //购物车全部列表数据
        cartListAll: <CartType[]>[]
    }),
    getters: {
        //简化购物车列表数据
        cartList(state) {
            return state.cartListAll[0] || {}
        }
    },
    actions: {
        //获取购物车列表数据
        async getCartList() {
            let result = await reqCartList()
            if (result.code == 200) {
                this.cartListAll = result.data
            }
        },
        //删除购物车某一个产品
        async delCartListById(skuId: string) {
            let result = await reqDelCartById(skuId)
            if (result.code == 200) {
                return 'ok'
            } else {
                Promise.reject(new Error('fail'))
            }
        },
        //修改购物车某一个产品的选中状态
        async updateCheckedById({skuId, isChecked}: {skuId: string; isChecked: string}) {
            let result = await reqUpdateChekedById(skuId, isChecked)
            if (result.code == 200) {
                return 'ok'
            } else {
                Promise.reject(new Error('fail'))
            }
        },
        //删除全部勾选的产品
        delAllCheckedCart() {
            let promiseAll: Promise<any>[] = []
            this.cartList.cartInfoList.forEach((item) => {
                let promise = item.isChecked == 1 ? this.delCartListById(String(item.skuId)) : null
                promiseAll.push(promise!)
            })
            //只要全部的p1|p2....都成功，返回结果即为成功;如果有一个失败，返回即为失败结果
            return Promise.all(promiseAll)
        },
        //修改全部产品的状态
        updateAllCartIsChecked(isChecked: string) {
            let promiseAll: Promise<any>[] = []
            this.cartList.cartInfoList.forEach((item) => {
                let promise = this.updateCheckedById({skuId: String(item.skuId), isChecked})
                promiseAll.push(promise!)
            })
            return Promise.all(promiseAll)
        }
    }
})
